package cn.stylefeng.guns.modular.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.modular.config.MinAppConfiguration;
import cn.stylefeng.guns.modular.service.MiniAppUserService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author 李宝嘉
 * @Date 2021/11/24 14:38
 */
@RestController
@RequestMapping("/miniapp/user")
public class MiniAppUserController {
    @Resource
    public MiniAppUserService miniAppUserService;

    @GetMapping("/login")
    public ResponseData login(@RequestParam String code, @RequestParam(defaultValue = "") String token) {
        final WxMaService wxService = MinAppConfiguration.getWxMaService();
        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            String result = miniAppUserService.login(session, token);
            return new SuccessResponseData(result);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return ResponseData.error("登录失败");
        }
    }
}
